<template>
  <div id="suspended">
    <a-divider>日新图查询</a-divider>
    <a-form :label-col="{ span: 7 }" :wrapper-col="{ span: 17 }">
      <a-form-item label="开始时间">
        <a-date-picker
          v-model="startTime"
          format="YYYY-MM-DD"
          :disabled-date="disabledStartDate"
          placeholder="开始时间(必选)"
          @openChange="handleStartOpenChange"
          @change="startDateChange"
      /></a-form-item>
      <a-form-item label="结束时间"
        ><a-date-picker
          v-model="endTime"
          format="YYYY-MM-DD"
          :disabled-date="disabledEndDate"
          placeholder="结束时间(必选)"
          @openChange="handleEndOpenChange"
          @change="endDateChange"
      /></a-form-item>
      <a-button-group>
        <a-button
          type="primary"
          @click="draw"
          title="点击绘制查询范围，默认全省范围"
          :disabled="queryDisabled"
          ><a-icon type="gateway" />绘制</a-button
        >
        <a-button
          type="primary"
          @click="query"
          :disabled="queryDisabled"
          :title="queryTitle"
          ><a-icon type="search" />查询</a-button
        >
        <a-button
          type="info"
          @click="clearMaps"
          title="关闭所有已经显示的日新图"
          ><a-icon type="redo" />重置</a-button
        >
      </a-button-group>
    </a-form>
    <div>
      <calendar-index ref="CalendarIndex" />
    </div>
  </div>
</template>

<script>
import elasticsearch from "elasticsearch";
import moment from "moment";
import CalendarIndex from "./CalendarIndex.vue";
export default {
  data() {
    return {
      queryDisabled: false,
      endOpen: false,
      queryTitle: "请选择时间范围",
      currentdate: "未选择",
      mapnumber: "未选择",
      polygon: [],
      startDate: null,
      endDate: null,
      startTime: null,
      endTime: null,

      Allmaps: null,
      AllmapsKeyVelue: {},
      mapsDate: "",
      isMessage: false,
    };
  },
  computed: {
    map() {
      return this.$store.state.map;
    },
    drawer() {
      return this.$store.state.drawer;
    },
    mapLableFeatureGroup() {
      return this.$store.state.mapLableFeatureGroup;
    },
  },
  components: {
    CalendarIndex,
  },
  mounted() {
    this.endTime = moment();
    this.startTime = moment().subtract(7, "days");
    this.startDateChange();
    this.endDateChange();
  },
  methods: {
    disabledStartDate(startTime) {
      const endTime = this.endTime;
      if (!startTime || !endTime) {
        return false;
      }
      return startTime.valueOf() > endTime.valueOf();
    },
    disabledEndDate(endTime) {
      const startTime = this.startTime;
      if (!endTime || !startTime) {
        return false;
      }
      return startTime.valueOf() >= endTime.valueOf();
    },
    handleStartOpenChange(open) {
      if (!open) {
        this.endOpen = true;
      }
    },
    handleEndOpenChange(open) {
      this.endOpen = open;
    },
    startDateChange() {
      this.startDate = null;
      this.startDate = Date.parse(
        new Date(Date.parse(this.startTime.toString().replace(/-/g, "/")))
      );
      if (this.endDate) {
        this.queryDisabled = false;
        this.queryTitle = "点击查询";
      }
      this.$refs.CalendarIndex.startDate = this.startDate;
      console.log("日新开始时间", this.startDate);
    },
    endDateChange() {
      this.endDate = null;
      this.endDate = Date.parse(
        new Date(Date.parse(this.endTime.toString().replace(/-/g, "/")))
      );
      if (this.startDate) {
        this.queryDisabled = false;
        this.queryTitle = "点击查询";
      }
      this.$refs.CalendarIndex.endDate = this.endDate;
      console.log("日新结束时间", this.endDate);
    },
    //绘制多边形
    draw() {
      this.clearDraw();
      this.drawer.RectangleDrawer.enable();
      this.getDrawedLayer();
    },
    //绘制事件监听，将绘制的多边形组织成范围数据
    getDrawedLayer() {
      this.map.once("draw:created", (e) => {
        console.log("created", e.layer.toGeoJSON());
        var points = e.layer.toGeoJSON().geometry.coordinates[0];
        this.polygon = points;
        e.layer
          .setStyle({
            fillOpacity: 0.05,
          })
          .addTo(this.mapLableFeatureGroup);
      });
    },
    //根据条件查询日新图
    query() {
      this.clearData();
      let esurl = window.getServiceUrl("", window.servicesPorts.es);
      console.log(esurl);
      var that = this;
      var client = new elasticsearch.Client({
        host: `${esurl.split("//")[0]}//elastic:Supermap@123@${
          esurl.split("//")[1]
        }`,
      });
      if (this.polygon.length < 3) {
        this.polygon = [
          [108.794523270157, 30.1236125771365],
          [114.265314262773, 30.1236125771365],
          [114.265314262773, 24.6333135713786],
          [108.794523270157, 24.6333135713786],
          [108.794523270157, 30.1236125771365],
        ];
      }
      var querybody = {
        from: 0,
        size: 10000,
        query: {
          bool: {
            must: {
              geo_shape: {
                geom: {
                  shape: {
                    type: "polygon",
                    coordinates: [this.polygon],
                  },
                  relation: "intersects",
                },
              },
            },
            filter: {
              range: { imagedate: { gte: this.startDate, lt: this.endDate } },
            },
          },
        },
      };

      client.search(
        {
          index: "hn_timeline",
          type: "_doc",
          body: JSON.stringify(querybody),
        },
        function (err, resp) {
          if (err) {
            console.log("查询失败");
          } else if (resp) {
            that.dealmaps(resp.hits.hits);

            console.log("日新查询结果", resp.hits);
          }
        }
      );

      // 从服务器查询日新图
      // var raw = JSON.stringify({
      //   queryGeometry: {
      //     coordinates: [JSON.parse(JSON.stringify(this.polygon))],
      //     type: "Polygon",
      //   },
      // });
      // var requestOptions = {
      //   method: "POST",
      //   headers: {
      //     "Content-type": "application/json;charset=UTF-8",
      //   },
      //   body: raw,
      // };
      // fetch("https://img.net/v1/metadata/search/timeline", requestOptions)
      //   .then((response) => response.text())
      //   .then((result) => this.dealmaps(JSON.parse(result)))
      //   .catch((error) => console.log("error", error));
    },
    //存储查询到的日新图
    dealmaps(result) {
      if (!result.length) {
        this.$message.destroy();
        this.$message.info("未查询到数据");
        return;
      }
      this.Allmaps = [];
      result.forEach((M) => {
        let item = M._source;
        item.checked = false;
        this.Allmaps.push(item);
      });

      let A = this.AllmapsKeyVelue;
      this.Allmaps.forEach(function (item) {
        A[item.appid] = item;
      });

      this.$refs.CalendarIndex.dataInfoTree(this.Allmaps);
      this.$refs.CalendarIndex.visible = true;
      //  setTimeout((this.$refs.CalendarIndex.loading = false), 3000);
    },
    //清除绘制图案
    clearDraw() {
      this.drawer.RectangleDrawer.disable();
      this.$store.state.mapLableFeatureGroup.clearLayers();
    },
    //移除图层
    clearMaps() {
      this.clearDraw();

      this.endTime = moment().format("YYYY-MM-DD");
      this.startTime = moment().subtract(7, "days").format("YYYY-MM-DD");
      this.startDateChange();
      this.endDateChange();
      this.$refs.CalendarIndex.onClose();
    },
    //清除查询缓存
    clearData() {
      this.Allmaps = null;
      this.AllmapsKeyVelue = {};
      if (this.$refs.CalendarIndex.visible) {
        this.$refs.CalendarIndex.onClose();
        this.$refs.CalendarIndex.loading = true;
      }
    },
  },
};
</script>

<style lang="less">
.list-card {
  margin-top: 10px !important;
  .ant-card-head {
    font-size: 8px !important;
  }
  .ant-card-body {
    padding: 6px;
    overflow-y: scroll;
    max-height: 55vh;
    .list {
      border-top: 0px solid #eee;
      margin-top: 5px;
      .ant-card {
        .ant-card-head {
          text-align: inherit !important;
          font-size: 5px !important;
        }
        font-size: 4px;
        border-radius: 0.2rem;
        border: 1px solid #e8e8e8;
        text-align: inherit;
        box-shadow: 0.5px 0.5px 0.5px #b3b6b8;
        .ant-card-body {
          max-height: 185px;
          overflow-y: scroll;
        }

        .item-title {
          width: 98%;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }

      // margin-right: 10px;
    }
  }
}
</style>
